<?php

namespace App\Service;
use App\Traits\JsonResponse;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Support\Facades\Log;

class MiniProgramService
{

    use JsonResponse;

    /**
     * 发送HTTP请求
     * @param $code
     * @param $http
     * @return array|bool|false|float|int|object|string|null
     */
    public function getOpenID($code,$http)
    {
        //完整参数
        $param = [];
        $param[] = 'appid=' .config('app.wechat_miniprogram_config.appid');
        $param[] = 'secret=' . config('app.wechat_miniprogram_config.secret');
        $param[] = 'js_code=' . $code;
        $param[] = 'grant_type=authorization_code';
        $params = implode('&', $param);    //用&符号连起来
        $url = config('app.wechat_miniprogram_config.openid_url') . '?' . $params;    // 拼接的请求地址

        return $http->HttpRequest($url,'GET');

    }

    /**
     * 获取小程序accessToken
     * @param $http
     * @param $cache
     * @return mixed
     */
    public function getAccessToken($http,$cache){
        try {
            $access_token = $cache::getKey('access_token_' . config('app.wechat_miniprogram_config.appid'));
        }catch (\Exception $e){
            return $this->errorReturn(10001, $e->getMessage());
        }

        if ($access_token) {
            return $this->successReturn(10000,'成功',$access_token);
        } else {

            //完整参数
            $param = [];
            $param[] = 'appid=' .config('app.wechat_miniprogram_config.appid');
            $param[] = 'secret=' . config('app.wechat_miniprogram_config.secret');
            $param[] = 'grant_type=client_credential';
            $params = implode('&', $param);    //用&符号连起来
            $url = config('app.wechat_miniprogram_config.access_token_url') . '?' . $params;    // 拼接的请求地址
            try {
                $result = $http->HttpRequest($url,'GET');
            }catch (\Exception $e){
                return $this->errorReturn(10001, $e->getMessage());
            }
            /*
             * 成功
             * {
             *       "access_token": "36_SMg6PGIPme0DEKRns8HqqACGa-KmOn5UGoWa-yDkGK-iH9M6gpXaxo-d5v1wN2eX6bbMJTQVGR0A7L7U4ifZSe43flRcO4z43NvnNdhFIb1YDrM7DFS9vvUIzNn47H8p1AfLy1NsSaLixmXnSJWbAJADUH",
             *       "expires_in": 7200
             *   }
             * 失败
             * {
             *       "errcode": 40125,
             *       "errmsg": "invalid appsecret, view more at http://t.cn/RAEkdVq"
             *   }
             * */

            $access_token = isset($result['access_token']) ? $result['access_token'] : '';
            if($access_token){
                try {
                    $cache::setexKey('access_token_' . config('app.wechat_miniprogram_config.appid'),$access_token,7200);
                }catch (\Exception $e){
                    return $this->errorReturn(10001, $e->getMessage());
                }

                return $this->successReturn(10000,'成功',$access_token);
            }
            return $this->errorReturn(10001, '获取accessToken失败');
        }
    }

    /**
     * @param $http
     * @param $access_token
     * @param array $data
     * @return false|\Illuminate\Http\JsonResponse|string
     */
    public function getCreateQrcode($http,$access_token,$data=[]){

        if(!$access_token){
            return tips(-1,'error','accessToken无效');
        }

        $url = config('app.wechat_miniprogram_config.create_qrcode_url').'?access_token='.$access_token;

        $params = [
            'access_token' => $access_token,
            'path' => config('app.wechat_miniprogram_config.qrcode_url')."?store=".$data['store']."&aid=".$data['active_id']."&cid=store"
        ];

        try {
            $result = $http->HttpRequest($url, 'POST', $params);
                /*  {
                 *      "errcode": 0,
                 *      "errmsg": "ok",
                 *      "contentType": "image/jpeg",
                 *      "buffer": Buffer
                 *   }
                 * */
        }catch (\Exception $e){
            Log::debug('生成二维码失败'.$e->getMessage());
            return $this->errorReturn(10001, $e->getMessage());
        }
        if(is_json($result) === false){
            return $this->successReturn(10000,'生成成功',self::data_uri($result,'image/png'));
        }else{
            return $this->errorReturn(10001, '生成失败');

        }
    }

    /**
     * 二进制流内容转换成base64图片
     * @param $contents
     * @param $type
     * @return string
     */
    public static function data_uri($contents, $type)
    {
        $base64 = base64_encode($contents);
        return ('data:' . $type . ';base64,' . $base64);
    }

    /**
     * 检验数据的真实性，并且获取解密后的明文.
     * @param $encryptedData string 加密的用户数据
     * @param $iv string 与用户数据一同返回的初始向量
     * @param $data string 解密后的原文
     *
     * @return int 成功0，失败返回对应的错误码
     */
    public function decryptData($Key, $encryptedData, $iv, &$data)
    {
        if (strlen($Key) != 24) {
            return -41001;
        }
        $aesKey = base64_decode($Key);


        if (strlen($iv) != 24) {
            return -41002;
        }
        $aesIV = base64_decode($iv);

        $aesCipher = base64_decode($encryptedData);

        $result = openssl_decrypt($aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);

        $dataObj = json_decode($result);
        if ($dataObj == NULL) {
            return -41003;
        }
        if ($dataObj->watermark->appid != config('app.wechat_miniprogram_config.appid')) {
            return -41003;
        }
        $data = $result;
        return 0;
    }
}
